from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django.core.cache import cache

from apps.areas.models import Area


# Create your views here.


class AreaView(View):

    def get(self, request):

        # 查询缓存数据
        province_list = cache.get('province')

        if province_list is None:

            province = Area.objects.filter(parent_id=None)

            province_list = []

            for pro in province:
                province_list.append({
                    'id': pro.id,
                    'name': pro.name
                })
            # 存储缓存数据
            # key value expire
            cache.set('province', province_list, 24 * 3600)

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})


class SubAreaView(View):

    def get(self, request, id):

        data_list = cache.get('city:%s' % id)

        if data_list is None:

            up_level = Area.objects.get(id=id)
            down_level = up_level.subs.all()

            data_list = []

            for item in down_level:
                data_list.append({
                    'id': item.id,
                    'name': item.name
                })

            cache.set('city:%s' % id, data_list, 24 * 3600)

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': {'subs': data_list}})
